import random


from django.http import HttpResponse, JsonResponse
from django.views import View
# Create your views here.
from django_redis import get_redis_connection

from celery_task.sms.tasks import send_code
from meiduo_mall.libs.captcha.captcha import captcha
from verification import contains
from meiduo_mall.utils.response_code import RETCODE
import logging
from celery_task.sms.yuntongxun.sms import CCP


logger = logging.getLogger('django')

class ImageCode(View):
    '''生成图形验证码并保存到redis数据库'''
    def get(self, request, uuid):

        name, image_data, image_bytes = captcha.generate_captcha()
        conn_redis = get_redis_connection('verify')
        conn_redis.setex(uuid, contains.IMAGE_CODE_TIME, image_data)
        return HttpResponse(image_bytes,content_type='image')


class ImageSmsVerify(View):
    '''验证图形码后发送短信验证码并保存到redis'''
    # url = this.host + '/sms_codes/' + this.mobile + '/?image_code=' + this.image_code + '&uuid=' + this.uuid;
    def get(self, request, mobile):
        '''图片验证码校验和发送短信验证码'''

        # 注意get得不到值不会报错
        client_image_code = request.GET.get('image_code')
        client_uuid = request.GET.get('uuid')

        # 前端显示60秒，但客户刷新页面却无效，故需后端也加以验证60秒
        # 保存redis手机号的状态，与前端60秒一致，防止绕过前端突破60秒的限制
        conn_redis = get_redis_connection('verify')
        send_flag = conn_redis.get('send_%s' % mobile)
        if send_flag:
            return JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'请求过于频繁'})

        # print(send_flag)

        # 验证二维码
        if not all([client_image_code, client_uuid]):
            return JsonResponse({'code': RETCODE.NECESSARYPARAMERR,'errmsg':'缺少参数'})
        server_image_code = conn_redis.get(client_uuid)
        if not server_image_code:
            return JsonResponse({'code': RETCODE.IMAGECODEERR,'errmsg': '图形验证码失效'})
        # 删除图形验证码，保证图形验证码只能使用一次
        conn_redis.delete(client_uuid)
        # 注意图形验证码的大小写和解码，从redis数据库取出来的数据都是二进制数据
        server_image_code = server_image_code.decode()
        if server_image_code.lower() != client_image_code.lower():
            return JsonResponse({'code': RETCODE.IMAGECODEERR,'errmsg':'图形验证码错误'})

        # 随机验证码
        sms_code = '%06d' % random.randint(0,999999)

        # 管道
        pl = conn_redis.pipeline()
        pl.setex('sms_%s' % mobile,contains.SMS_CODE_TIME,sms_code)
        pl.setex('send_%s' % mobile, 60, 1)
        pl.execute()

        # 日志
        logger.info(sms_code)
        # print(mobile)
        # CCP().send_template_sms(mobile,[sms_code,contains.SMS_CODE_TIME//60],1)
        send_code.delay(mobile,sms_code)
        return JsonResponse({'code':RETCODE.OK,'errmsg':'发送短信成功'})



